//
//  AppDelegate.swift
//  RCWeibo
//
//  Created by CL on 15/12/12.
//  Copyright © 2015年 CL. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        //加载用户数据
//        let account =  RCUserAccount.loadFromSandbox()
//        print(account)
        
//        print(isNewVersion())
        
        //设置主题颜色
        setThemeColor()
        //手动创建根视图
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.clearColor()
        //设置成keywindow
        window?.makeKeyAndVisible()
        
        //注册通知
        registerNotification()
        
        window?.rootViewController = defaultViewController()
//            RCNewFeatureCollectionViewController()
//            RCMainViewController()
        
        
        return true
    }
    
    //注册通知
    private func registerNotification(){
        //object 如果不为空: 通知  ,  nil: 对应广播

    defaultNotification.addObserver(self, selector: "switchRootVC:", name: WBSwitchRootVCNote, object: nil)
        
    }
    
    @objc private func switchRootVC(note: NSNotification){
    
//        print(note.object)
        
        
        window?.rootViewController = (note.object ?? "").isEqual("") ?  RCWelcomeViewController() : RCMainViewController()
        
        
    }
    
    //程序运行时选择的默认vc
    private func defaultViewController() -> UIViewController{
    
        if isNewVersion() {
        
            return RCNewFeatureCollectionViewController()
        }else if RCUserAccountViewModel().isLogin {
        
            return RCWelcomeViewController()
        }else {
        
            return RCMainViewController()
        }
        
    }
    
    //MARK:
    //MARK:判断当前是否是新版本
    private func isNewVersion() -> Bool {
    
        //获取当前版本
        let info = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
        let currentVersion = Double(info as! String)!

        //获取沙盒存储版本
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let versionKey = "versionKey"
        let lastVersion = userDefaults.doubleForKey(versionKey)
        //存储当前版本
        userDefaults.setDouble(currentVersion, forKey: versionKey)
        userDefaults.synchronize()
        
        //比较
        return currentVersion > lastVersion
    }
    
    private func setThemeColor(){
    
        //在appdelegate里面事先设置颜色用appearance()
        UITabBar.appearance().tintColor = themeColor
        UINavigationBar.appearance().tintColor = themeColor
        
    }



}

